package com.yuzhi.common.jackson;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.yuzhi.common.annotation.DictFormat;
import com.yuzhi.common.core.service.DictService;

import java.io.IOException;


public class DictTranCodeSerializer extends StdSerializer<Object> implements ContextualSerializer {

    private DictFormat dictTranFormat;

    public DictTranCodeSerializer() {
        super(Object.class);
    }

    public void setDictTranFormat(DictFormat dictTranFormat) {
        this.dictTranFormat = dictTranFormat;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (ObjectUtil.isNull(value)) {
            gen.writeObject(value);
            return;
        }
        // 通过数据字典类型和value获取name
        gen.writeObject(value);
        gen.writeFieldName(gen.getOutputContext().getCurrentName() + "Desc");
        DictService dictService = SpringUtil.getBean(DictService.class);
        String nameByCode = dictService.getDictLabel(dictTranFormat.defaultValue(),(String) value);
        gen.writeString(StrUtil.isNotBlank(nameByCode) ? nameByCode : "");
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (ObjectUtil.isNull(beanProperty)) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}
